package com.kylin.system.controller;

import com.kylin.common.core.beans.ResultBean;
import com.kylin.common.core.entity.DataEntity;
import com.kylin.common.core.entity.Page;
import com.kylin.common.core.exception.CheckException;
import com.kylin.common.core.validator.Assert;
import com.kylin.common.core.validator.BeanValidator;
import com.kylin.common.datascope.annotation.DataScope;
import com.kylin.common.log.annotation.Log;
import com.kylin.common.log.enums.BusinessType;
import com.kylin.common.security.util.SecurityUtils;
import com.kylin.system.entity.SysDept;
import com.kylin.system.entity.SysMenu;
import com.kylin.system.service.SysDeptService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 部门信息
 * 
 * @author wuhao
 */
@RestController
@RequestMapping("/dept")
public class SysDeptController
{
    @Autowired
    private SysDeptService deptService;

    /**
     * 获取部门列表
     */
    @DataScope
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public ResultBean<Page<SysDept>> list(SysDept dept)
    {
        Long parentId = dept.getParentId();
        // 构建搜索
        dept.getQueryWrapper()
                .like(StringUtils.isNotBlank(dept.getDeptName()),"dept_name", dept.getDeptName())
                .like(StringUtils.isNotBlank(dept.getStatus()), "status", dept.getStatus())
                .eq(parentId != null, "parent_id", parentId)
                .orderByAsc("tree_sorts").orderByDesc("create_time");
        List<SysDept> depts =  deptService.list(dept);

        if(parentId == null) {
            parentId = 0L;
        }

        List<SysDept> deptTreeList = deptService.convertChildList(depts, parentId );

        Page<SysDept> page = new Page<>();
        page.setRecords(deptTreeList);
        page.setTotal(deptTreeList.size());
        return ResultBean.onSuccess(page);
    }

    /**
     * 查询部门列表（排除节点） 新增时用
     */
    @DataScope
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public ResultBean<List<SysDept>> excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        SysDept where = new SysDept();
        where.getQueryWrapper()
                .notLike("parent_ids", deptId+",")
                .ne("id", deptId)
                .eq("status", DataEntity.STATUS_NORMAL);
        List<SysDept> depts = deptService.list(where);
        return ResultBean.onSuccess(depts);

    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public ResultBean<SysDept> getInfo(@PathVariable Long deptId)
    {
        // 非空校验
        Assert.isBlank("查询编号不能为空", deptId);
        return ResultBean.onSuccess(deptService.getById(deptId));
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public ResultBean<Object> add(@RequestBody SysDept dept)
    {
        // 参数校验
        BeanValidator.validate(dept);
        deptService.save(dept);
        return ResultBean.onSuccess();
    }

    /*
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResultBean<Object> edit(@RequestBody SysDept dept)
    {
        // 参数校验
        BeanValidator.validate(dept);
        // 停用部门的时候需要检测是否有未停用的子部门
        if (StringUtils.equals(DataEntity.STATUS_DISABLE, dept.getStatus())
                && !deptService.selectNormalChildrenById(dept.getId()).isEmpty())
        {
            throw new CheckException("该部门包含未停用的子部门！");
        }
        deptService.save(dept);
        return ResultBean.onSuccess();
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public ResultBean<Object> remove(@PathVariable Long deptId)
    {
        Assert.isBlank("请选择需要删除的数据", deptId);
        if(!deptService.listChildren(deptId).isEmpty()) {
            throw new CheckException("存在下级部门，不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            throw new CheckException("部门存在用户,不允许删除");
        }

        deptService.delete(deptId);
        return ResultBean.onSuccess();
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/tree")
    public ResultBean<List<SysDept>> treeSelect(SysDept dept)
    {
        Long deptId = SecurityUtils.getLoginUser().getDeptId();
        SysDept where = new SysDept();
        where.getQueryWrapper().like("parent_ids",deptId ).or().eq("id",deptId );
        List<SysDept> deptList = deptService.list(where);

        SysDept owner = deptList.stream().filter(item -> item.getId().equals(deptId)).findFirst().get();
        return ResultBean.onSuccess(deptService.convertChildList(deptList, owner.getParentId()));
//        List<SysDept> depts = deptService.list(new SysDept());
//        return ResultBean.onSuccess(deptService.convertChildList(depts, 0L ));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public ResultBean<Object> roleDeptTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysDept> depts = deptService.list(new SysDept());
        Map<String,Object> data = new HashMap<>();
        data.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        data.put("depts", deptService.convertChildList(depts, 0L));
        return ResultBean.onSuccess(data);
    }

}
